package com.jinkaimen.kqb.ui.activity;

import android.annotation.TargetApi;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.widget.Toast;

import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.BridgeWebViewClient;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.ht.baselibs.core.EventCenter;
import com.ht.baselibs.ui.base.BaseActivity;
import com.ht.baselibs.utils.ActivityUtils;
import com.ht.baselibs.utils.SharedPreferencesUtils;
import com.jinkaimen.kqb.R;
import com.jinkaimen.kqb.constant.Constants;
import com.jinkaimen.kqb.ui.activity.addmerchant.RegisterAddActivity;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.utils.TbsLog;

/**
 * Created by Admin on 2017/9/5.
 */

public class H5updatePicActivity extends BaseActivity {
    private BridgeWebView webView;
    private ValueCallback<Uri> mUploadMessage;
    public ValueCallback<Uri[]> uploadMessage;
    public static final int REQUEST_SELECT_FILE = 100;
    private final static int FILECHOOSER_RESULTCODE = 2;

    @Override
    protected boolean isStaticPage() {
        return true;
    }

    @Override
    protected void initTitleBar() {
        mTitleBarView.setTitleText("实名认证");
    }

    @Override
    protected int initContentView() {
        return R.layout.activity_h5_update_pic;
    }

    @Override
    protected void initChildView() {
        webView = (BridgeWebView) findViewById(R.id.x5webview);

        webView.setWebViewClient(new MyWebViewClient(webView));
//        doWebView();
        setWebChromeClient();
        //     webView.setDefaultHandler(new myHadlerCallBack());
        String token = SharedPreferencesUtils.getString(Constants.TOKEN, "");
        webView.loadUrl("http://hss.qianbaojiajia.com/earn/certification" + Constants.TOKEN_TITLE + token);
        String clientid = SharedPreferencesUtils.getString(Constants.CID, "");
        Log.e("token = ", token);
        Log.e("clientid = ", clientid);

        //必须和js函数名字一致，注册好具体执行回调函数，类似java实现类。
        webView.registerHandler("aadMerchant", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                ActivityUtils.startActivity(H5updatePicActivity.this, RegisterAddActivity.class);
            }
        });


        WebSettings webSetting = webView.getSettings();
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(true);
        webSetting.setBuiltInZoomControls(true);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(false);
        // webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true);
        // webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setJavaScriptEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        webSetting.setAppCachePath(this.getDir("appcache", 0).getPath());
        webSetting.setDatabasePath(this.getDir("databases", 0).getPath());
        webSetting.setGeolocationDatabasePath(this.getDir("geolocation", 0)
                .getPath());
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        // webSetting.setPreFectch(true);
        long time = System.currentTimeMillis();
//        if (mIntentUrl == null) {
//            webView.loadUrl(mHomeUrl);
//        } else {
//            webView.loadUrl(mIntentUrl.toString());
//        }
        TbsLog.d("time-cost", "cost time: "
                + (System.currentTimeMillis() - time));


    }

    @Override
    protected void initChildData() {

    }

    @Override
    protected void setChildViewListener() {


    }

    @Override
    public void onClick(View v) {
        super.onClick(v);

    }

    @Override
    public void onEvent(EventCenter eventCenter) {
        switch (eventCenter.eventCode) {

        }
    }

    private void doWebView() {
        webView.setWebChromeClient(new WebChromeClient() {

            // For 3.0+ Devices (Start)
            // onActivityResult attached before constructor
            public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);
            }


            // For Lollipop 5.0+ Devices
            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
                if (uploadMessage != null) {
                    uploadMessage.onReceiveValue(null);
                    uploadMessage = null;
                }

                uploadMessage = filePathCallback;

                Intent intent = fileChooserParams.createIntent();
                try {
                    startActivityForResult(intent, REQUEST_SELECT_FILE);
                } catch (ActivityNotFoundException e) {
                    uploadMessage = null;
                    Toast.makeText(H5updatePicActivity.this, "Cannot Open File Chooser", Toast.LENGTH_LONG).show();
                    return false;
                }
                return true;
            }

            //For Android 4.1 only
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                mUploadMessage = uploadMsg;
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("image/*");
                startActivityForResult(Intent.createChooser(intent, "File Browser"), FILECHOOSER_RESULTCODE);
            }

            protected void openFileChooser(ValueCallback<Uri> uploadMsg) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
            }

        });
    }

    class MyWebViewClient extends BridgeWebViewClient {

        public MyWebViewClient(BridgeWebView webView) {
            super(webView);
        }

    }

    private ValueCallback<Uri> mUploadFile;
    /**
     * 拍照/选择文件请求码
     */
    private static final int REQUEST_UPLOAD_FILE_CODE = 12343;

    private void setWebChromeClient() {
        if (null != webView) {
            webView.setWebChromeClient(new WebChromeClient() {
                // Andorid 4.1+
                public void openFileChooser(ValueCallback<Uri> uploadFile, String acceptType, String capture) {
                    openFileChooser(uploadFile);
                }

                // Andorid 3.0 +
                public void openFileChooser(ValueCallback<Uri> uploadFile, String acceptType) {
                    openFileChooser(uploadFile);
                }

                // Android 3.0
                public void openFileChooser(ValueCallback<Uri> uploadFile) {
                    // Toast.makeText(WebviewActivity.this, "上传文件/图片",Toast.LENGTH_SHORT).show();
                    mUploadFile = uploadFile;
                    startActivityForResult(Intent.createChooser(createCameraIntent(), "Image Browser"), REQUEST_UPLOAD_FILE_CODE);
                }
            });
        }
    }

    private Intent createCameraIntent() {
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//拍照
        //=======================================================
        Intent imageIntent = new Intent(Intent.ACTION_GET_CONTENT);//选择图片文件
        imageIntent.setType("image/*");
        //=======================================================
        return cameraIntent;
    }

}
